//
//  LwxChooseMoreWorldCityTableViewController.m
//  test
//
//  Created by 鲁万玺 on 2017/8/24.
//  Copyright © 2017年 鲁万玺. All rights reserved.
//

#import "LwxChooseMoreWorldCityTableViewController.h"
#import "ChooseMoreWorldCityTableViewCeTableViewCell.h"
#import "LwxChooseMoreCityHeadView.h"

@interface LwxChooseMoreWorldCityTableViewController ()<UISearchBarDelegate>

@property (nonatomic, strong)UISearchBar *searchBar;
@property (nonatomic, strong)NSMutableArray *chooseArr;
@property (nonatomic, strong)NSArray *hotArr;
@property (nonatomic, strong)NSArray *searchArr;

@property (nonatomic, strong)NSMutableArray *allArr;

@end

@implementation LwxChooseMoreWorldCityTableViewController

+ (instancetype)initWithBlock:(LwxChooseBlock)block
{
    LwxChooseMoreWorldCityTableViewController *vc = [[LwxChooseMoreWorldCityTableViewController alloc]init];
    vc.block = block;
    vc.maxCity = 3;
    return vc;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"确定" style:UIBarButtonItemStylePlain target:self action:@selector(rightClick:)];
    
    [self getData];
    
    self.tableView.tableHeaderView = ({
        UIView *titleView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 40)];
        self.searchBar = [[UISearchBar alloc]initWithFrame:CGRectMake(0,0,220/WIDTH_5S_SCALE,30)];
        self.searchBar.centerX = titleView.width/2;
        self.searchBar.centerY = titleView.height/2;
        [self.searchBar setCornerRadius:5];
        [self.searchBar setBorderWidth:1 borderColor:[UIColor whiteColor]];
        self.searchBar.barStyle = UIBarStyleDefault;
        self.searchBar.placeholder = @"搜索";
        self.searchBar.backgroundImage = [UIColor imageWithColor: [UIColor clearColor]];
        self.searchBar.delegate = self;
        UITextField *searchField = [self.searchBar valueForKey:@"searchField"];
        if (searchField)
        {
            [searchField setBackgroundColor:[UIColor clearColor]];
            searchField.textColor = [UIColor blackColor];
        }
        [titleView addSubview:self.searchBar];
        titleView;
    });
    self.tableView.tableFooterView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 0, 0)];
    [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([LwxChooseMoreCityHeadView class]) bundle:nil]  forHeaderFooterViewReuseIdentifier:NSStringFromClass([LwxChooseMoreCityHeadView class])];
}

- (void)getData
{
    self.chooseArr = [NSMutableArray array];
    self.searchArr = @[];
    self.hotArr = @[@"北京",@"上海",@"云南",@"法国",@"意大利",@"马来西亚",@"泰国"];
    self.allArr = [NSMutableArray arrayWithArray:@[self.hotArr]];
    
}

#pragma mark - UITableViewDelegate,UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.allArr.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [self.allArr[section] count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    ChooseMoreWorldCityTableViewCeTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([ChooseMoreWorldCityTableViewCeTableViewCell class])];
    if (!cell)
    {
        cell = [[NSBundle mainBundle] loadNibNamed:NSStringFromClass([ChooseMoreWorldCityTableViewCeTableViewCell class]) owner:nil options:nil].firstObject;
        cell.preservesSuperviewLayoutMargins = NO;
        cell.separatorInset = UIEdgeInsetsZero;
        cell.layoutMargins = UIEdgeInsetsZero;
    }
    cell.chooseBtn.selected = NO;
    for (NSString *str in self.chooseArr)
    {
        if ([self.allArr[indexPath.section][indexPath.row] isEqualToString:str])
        {
            cell.chooseBtn.selected = YES;
        }
    }
    cell.titleLabel.text = self.allArr[indexPath.section][indexPath.row];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    ChooseMoreWorldCityTableViewCeTableViewCell *cell = (ChooseMoreWorldCityTableViewCeTableViewCell *)[tableView cellForRowAtIndexPath:indexPath];
    if (cell.chooseBtn.selected)
    {
        //取消选中
        [self.chooseArr removeObject:cell.titleLabel.text];
        if (self.chooseArr.count == 0)
        {
            [self.allArr removeObject:self.chooseArr];
        }
    }
    else
    {
        //选中
        if (self.chooseArr.count >= self.maxCity)
        {
            [[HUDHelper sharedInstance]tipMessage:[NSString stringWithFormat:@"最多选择%ld个目的地",self.maxCity]];
            return;
        }
        [self.chooseArr addObject:cell.titleLabel.text];
        if (self.allArr[0] != self.chooseArr)
        {
            [self.allArr insertObject:self.chooseArr atIndex:0];
        }
    }
    cell.chooseBtn.selected = !cell.chooseBtn.selected;
    [self.tableView reloadData];
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 30;
}

- (nullable UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section;
{
    LwxChooseMoreCityHeadView *view = [tableView dequeueReusableHeaderFooterViewWithIdentifier:NSStringFromClass([LwxChooseMoreCityHeadView class])];
    if (self.allArr[section] == self.hotArr)
    {
        view.titleLabel.text = @"热门城市";
    }
    else if (self.allArr[section] == self.searchArr)
    {
        view.titleLabel.text = @"搜索到的城市";
    }
    else
    {
        view.titleLabel.text = @"已选中的城市";
    }
    view.contentView.backgroundColor = [UIColor lightGrayColor];
    return view;
}


#pragma mark - click
- (void)rightClick:(UIBarButtonItem *)sender
{
    if (self.chooseArr.count != 0)
    {
        self.block(self.chooseArr);
    }
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - UISearchBarDelegate
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    if ([self.searchBar.text isEqualToString:@""])
    {
        [self.allArr removeObject:self.searchBar];
    }
    else
    {
        self.searchArr = [self getdataWithFindStr:searchBar.text];
        [self.allArr insertObject:self.searchArr atIndex:1];
    }
    [self.tableView reloadData];
}

- (void)searchBarTextDidEndEditing:(UISearchBar *)searchBar
{
    if ([self.searchBar.text isEqualToString:@""])
    {
        [self.allArr removeObject:self.searchBar];
    }
}

#pragma mark - searchData
- (NSMutableArray *)getdataWithFindStr:(NSString *)str
{
    NSString *path1 = [[NSBundle mainBundle] pathForResource:@"Loaction" ofType:@"plist"];
    NSDictionary *dic = [[NSDictionary alloc] initWithContentsOfFile:path1][@"Location"];
    
    NSArray *arr = dic[@"Continent"];
    
    NSMutableArray *dataArr = [NSMutableArray array];
    
    dataArr = [self getArr:dataArr data:arr findStr:str];
    return dataArr;
}

- (NSMutableArray *)getArr:(NSMutableArray *)arr data:(NSArray *)data findStr:(NSString *)str
{
    for (id item in data)
    {
        if ([item isKindOfClass:[NSDictionary class]])
        {
            if ([item[@"Name"] rangeOfString:str].location != NSNotFound)
            {
                [arr addObject:item[@"Name"]];
            }
            if (item[@"CountryRegion"])
            {
                arr = [self getArr:arr data:item[@"CountryRegion"] findStr:str];
            }
            else if(item[@"State"])
            {
                arr = [self getArr:arr data:item[@"State"] findStr:str];
            }
            else if(item[@"City"])
            {
                arr = [self getArr:arr data:item[@"City"] findStr:str];
            }
        }
        else if ([item isKindOfClass:[NSArray class]])
        {
            arr = [self getArr:arr data:data findStr:str];
        }
    }
    return arr;
}

@end
